import { useState, useEffect } from "react";
import styles from "../css/IssueItem.module.scss"
import { formatTimestamp } from "../utils/tools.js"
import { useDispatch, useSelector } from "react-redux";
import { IStore, ITypeList } from "../redux/typings/index"
import { getType } from "../redux/typeList"
import { Tag } from "antd";
import { getUserById } from "../api/user"
import { IUserInfo } from "../redux/typings"
import { useNavigate } from "react-router-dom";
import { IIssueInfo } from "../typings";

interface IProps {
    issueItemData: IIssueInfo
}

// 每一条问答项目
const IssueItem = (props: IProps) => {
    const { typeList } = useSelector((state: IStore) => state.type);
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const colorArr = ["#108ee9", "#2db7f5", "#f50", "green", "#87d068", "blue", "red", "purple"];
    const [userInfo, setUserInfo] = useState<IUserInfo>({}); //存储用户信息

    useEffect(() => {
        if (!typeList.length) {
            // 发送请求
            dispatch((getType as any)())
        }
        const fetchData = async () => {
            const res = await getUserById(props.issueItemData.userId);
            setUserInfo(res.data.data)
        }
        fetchData()
    }, [])

    // 跳转问答详情页
    const goToIsssueDetail = () => {
        const id = props.issueItemData._id;
        navigate(`/issues/${id}`);
    }

    const type = typeList.find(item => item._id === props.issueItemData.typeId)
    return (
        <div className={styles.container}>
            {/* 回答数 */}
            <div className={styles.issueNum}>
                <div>{props.issueItemData.commentNumber}</div>
                <div>回答</div>
            </div>
            {/* 浏览数 */}
            <div className={styles.issueNum}>
                <div>{props.issueItemData.scanNumber}</div>
                <div>浏览</div>
            </div>
            {/* 问题内容 */}
            <div className={styles.issueContainer}>
                <div className={styles.top} onClick={goToIsssueDetail}>{props.issueItemData.issueTitle}</div>
                <div className={styles.bottom}>
                    <div className={styles.left}>
                        <Tag color={colorArr[typeList.indexOf(type as ITypeList) % colorArr.length]}>{type?.typeName}</Tag>
                    </div>
                    <div className={styles.right}>
                        <Tag color="orange">{userInfo.nickname}</Tag>
                        {/* 日期 */}
                        <span>{formatTimestamp(+props.issueItemData.issueDate)}</span>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default IssueItem
